package br.com.fiap.mercadinho.bean;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import br.com.fiap.mercadinho.common.DAOException;
import br.com.fiap.mercadinho.dao.OrderDAO;
import br.com.fiap.mercadinho.dao.ProductOrderDAO;
import br.com.fiap.mercadinho.dao.StockDAO;

@SuppressWarnings("serial")
public class Order implements Serializable {

	private Integer id;
	private Customer customer;
	private Map<Integer, Product> products = new HashMap<Integer, Product>();

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public void setId(String id) {
		if (id != null && !id.equals("")) {
			this.id = Integer.valueOf(id);
		} else {
			this.id = 0;
		}
	}

	public Customer getCustomer() {
		return customer;
	}

	public void setCustomer(Customer customer) {
		this.customer = customer;
	}

	public Map<Integer, Product> getProducts() {
		return products;
	}

	public void setProducts(Map<Integer, Product> products) {
		this.products = products;
	}

	public void addProduct(Integer id, Integer quantity) {
		Product prod = new Product();
		prod.setId(id);
		prod.setQuantity(quantity);
		this.products.put(prod.getId(), prod);
	}

	public void addProduct(Product prod, Integer quantity) {

		Product prd = new Product();
		prd.setId(prod.getId());
		prd.setDescription(prod.getDescription());
		prd.setPrice(prod.getPrice());
		prd.setQuantity(quantity);

		prod.setQuantity(quantity);
		// if the product was selected by user in the past, sum the two.
		if (this.products.get(prod.getId()) != null) {
			Integer newQuantity = quantity
					+ this.products.get(prd.getId()).getQuantity();
			prd.setQuantity(newQuantity);
		}
		this.products.put(prd.getId(), prd);
	}

	public void removeProduct(Product prod) {
		this.products.remove(prod.getId());
	}

	public void setCustomerId(String id) {
		if (this.customer == null) {
			this.customer = new Customer();
		}
		this.getCustomer().setId(id);
	}

	public Integer getCustomerId() {
		if (this.customer == null)
			return 0;
		else
			return this.customer.getId();
	}

	public void saveOrderWithProducts() throws DAOException {
		OrderDAO dao = new OrderDAO();
		ProductOrderDAO productOrderDAO = new ProductOrderDAO();
		StockDAO daoStockDAO = new StockDAO();
		dao.saveOrder(this);
		this.id = dao.getLastInsertId();
		productOrderDAO.saveOrderProducts(this);

		daoStockDAO.updateProductsQuantity(this.products);
	}

	public String getTotalOrderValue() {

		Double price = new Double(0);
		if (products != null && !products.isEmpty()) {
			Iterator<Product> prds = products.values().iterator();

			while (prds.hasNext()) {
				price += prds.next().getTotalPrice();
			}
		}
		return String.valueOf(price);
	}

}
